import { NextApiRequest, NextApiResponse } from 'next';
import OpenAI from 'openai';

if (!process.env.OPENAI_API_KEY) {
  throw new Error('Missing OPENAI_API_KEY environment variable');
}

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { text, language = 'zh' } = req.body;

    if (!text) {
      return res.status(400).json({ error: 'Text is required' });
    }

    const voice = language === 'zh' ? 'shimmer' : 'alloy';
    const response = await openai.audio.speech.create({
      model: 'tts-1',
      voice,
      input: text,
    });

    const arrayBuffer = await response.arrayBuffer();
    
    res.setHeader('Content-Type', 'audio/mpeg');
    res.setHeader('Content-Length', arrayBuffer.byteLength);
    res.send(Buffer.from(arrayBuffer));
  } catch (error) {
    console.error('Speech synthesis error:', error);
    res.status(500).json({ error: '语音合成失败，请稍后再试' });
  }
}